import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', redirect: '/layout' },
    { path: '/login', component: () => import('@/views/login/index.vue') },
    {
      path: '/layout',
      component: () => import('@/views/layout/index.vue'),
      redirect: '/report',
      children: [
        { path: '/user/information', component: () => import('@/views/personal/basicInformation.vue') },
        { path: '/user/avatar', component: () => import('@/views/personal/changeAvatar.vue') },
        { path: '/user/repsd', component: () => import('@/views/personal/resetPassword.vue') },
        { path: '/notice', component: () => import('@/views/notice/index.vue') },
        { path: '/report', component: () => import('@/views/report/index.vue') },
        { path: '/achievement', component: () => import('@/views/achievement/index.vue') },
        { path: '/manageNotice', component: () => import('@/views/notice/teacher.vue') },
        { path: '/resultGrade', component: () => import('@/views/achievement/resultGrade.vue') },
        { path: '/exper', component: () => import('@/views/report/exper.vue') }
      ]
    }
  ]
})

// 全局前置导航守卫
router.beforeEach((to, from, next) => {
  // 非权限页
  const notLimit = ['/login']
  if (to.path.includes(notLimit)) {
    return next()
  }

  // 权限页，判断有无token
  const userStore = useUserStore()
  const token = userStore.token
  if (token) {
    next()
  } else {
    next('/login')
  }

})

export default router
